package com.xzc.shopping.controller;

import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.model.domain.User;
import com.xzc.shopping.model.request.UserLoginRequest;
import com.xzc.shopping.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.xzc.shopping.constant.UserConstant.USER_LOGIN_STATE;


@CrossOrigin(origins = "http://localhost:3000") // 允许前端地址
@RestController
@RequestMapping("/user")
@Slf4j

public class UserController {


@Resource
private UserService userService;


    // 处理登录请求
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userName = userLoginRequest.getUserName();
        String userPassword = userLoginRequest.getPassword();
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        return  userService.userLogin(userName, userPassword, request);

    }

    @GetMapping("/check")
    public BaseResponse<User> checkLoginStatus(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user != null
                ? ResultUtils.success(user)
                : ResultUtils.error(ErrorCode.NOT_LOGIN);
    }
}
